Repository navigation
Convert the row tails of SimdUtils byte and float conversions with narrower vectors - #3289
Open
sebastienros wants to merge 3 commits into
Open
sebastienros wants to merge 3 commits into
sebastienros wants to merge 3 commits into
Conversation
…er vectors ByteToNormalizedFloat and FloatToByteSaturate converted the bytes after the last whole step of the widest vector one element at a time. The Reduce methods now convert whole pixels of that tail with 16-, 8-, or 4-element vector steps, with the same arithmetic per element, so the output is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
The main byte-to-float loop and its tail each declared the high and low parts of 1 / 255; the floats are only equal while both copies match, so they are now one pair of class constants. The 256-bit and 128-bit narrow steps explain their lane layout like the 512-bit step. The tail test also checks SimdUtils.FloatToByteSaturate (scale 1, used for associated pixels), which runs the same tail with another bound. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01871HTtWub3CsCnBstKx55h
|
|
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prerequisites
Description
SimdUtils.ByteToNormalizedFloatandSimdUtils.NormalizedFloatToByteSaturate/FloatToByteSaturate(and theirTAlphaforms) converted everything after the last whole step of the widest vector (64 bytes with AVX-512, 32 with AVX2, 16 with SSE) one element at a time; the byte-to-float remainder divided each byte by 255. Every row whose length is not a multiple of 16Rgba32pixels (with AVX-512) paid for up to 15 pixels in scalar code, and rows shorter than 16 pixels were converted in scalar code only. The blender converts each row toVector4and back, so every short span of a fill or a stroke paid two scalar tails.The investigation that this change follows (profiles, prototype, equality check, and the full benchmark code) is in the collapsed section at the end.
Change (
src/ImageSharp/Common/Helpers/SimdUtils.HwIntrinsics.cs):ByteToNormalizedFloatReduce<TAlpha>andFloatToByteSaturateReduce<TAlpha>now continue after the main loop with narrower vector steps, in new private methodsByteToNormalizedFloatTail<TAlpha>andFloatToByteSaturateTail<TAlpha>:FusedMultiplyAdd(f, high, f * low)with the same reciprocal parts; float to byte isTAlpha.Apply,ClampToFiniteto [0, 255 / scale] (NaN to 0), andConvertToInt32Native(x * scale + 0.5). After the clamp the integers are 0 to 255, so the truncating narrows give the bytes of the saturating narrow. The output is the same for every length and input.TAlphasees whole RGBA groups. Each step loads before it stores and the steps move forward, which the staging inRgba32CompatiblePixelOperations<TPixel>.Unpackand the three-byte packing inPackrely on (the reason for narrower steps instead of one overlapping vector).Tests (
tests/ImageSharp.Tests/Common/SimdUtilsTests.cs):ByteToNormalizedFloat_EveryShortLength_MatchesOracle_AtEveryVectorWidthandFloatToByteSaturate_EveryShortLength_MatchesOracle_AtEveryVectorWidthrun every length from 0 to 130 under each width (all features, AVX-512 off, AVX2 off, all intrinsics off) throughFeatureTestRunner, against a scalar oracle: byte / 255 in double, and NaN to 0, clamp, truncate(x * 255 + 0.5) for floats with NaN, infinities, signed zeros, and out-of-range values; and theAssociateOperator/UnassociateOperatorforms per pixel. With the 4-float step's rounding constant changed to 0.49 (a temporary change), the float test fails.Test run (macOS 15.8.3 arm64, .NET 10, with the PNG test inputs from Git LFS):
dotnet testoftests/ImageSharp.Testswith the filterSimdUtils|PixelOperations|PixelBlender|PorterDuff, in Release and in Debug: 44,132 passed, 12 failed, 1 skipped. The 12 failures arePorterDuffOutputIsCorrect, which fail the same way onmain(c6d486d): their reference images (Git LFS objects) were not fetched for this run.Measured (BenchmarkDotNet 0.15.8, .NET 10.0.15, Intel Xeon 2.30 GHz with AVX-512, shared cloud container; 5 warmup and 15 measured iterations of 100 ms; mean ± half of the 99.9% interval). The
RowConversionbenchmark at the end: one row ofRgba32toVector4(PixelOperations<Rgba32>.ToUnassociatedScaledVector4) and back (FromUnassociatedScaledVector4Destructive), the released package against this branch (Release build ofsrc/ImageSharp, referenced as an assembly by the same benchmark project: replace theSixLabors.ImageSharppackage reference with<Reference Include="SixLabors.ImageSharp" HintPath="<Release build of src/ImageSharp>/SixLabors.ImageSharp.dll" />):Rows that end with a tail are 1.2 to 6.7 times faster. Rows of whole 16-pixel steps are unchanged within the error, except 32 pixels to
Rgba32, 5% slower (11.6 ± 0.4 against 12.1 ± 0.1 ns). The equality check of the benchmark project (every length from 0 to 300 pixels, 20 random rows each, half of the float rows with special values) gives 0 differing bytes and floats between this branch and the prototype, which gives 0 against the released package.Not verified: AVX2-only and SSE-only machines (only through the feature switches of the tests on this AVX-512 machine), the tests on ARM64 (the ARM64 timing is below), and the effect on a real workload: the profiles of the SVG work in ImageSharp.Drawing put the scalar remainders at 4.6% to 21% of the samples of drawing workloads.
Measured on ARM64 (local, BenchmarkDotNet ShortRun)
BenchmarkDotNet 0.15.8,
Job.ShortRun(3 warmup and 3 measured iterations, 1 launch), .NET 10.0.15 (Arm64 RyuJIT), Apple M4 Pro (14 cores, 48 GB; 128-bit AdvSIMD, no 256- or 512-bit vectors), macOS 15.8.3; mean ± half of the 99.9% interval; two rounds,mainthen this branch, one benchmark process at a time. Both sides are Release builds ofsrc/ImageSharpfrom source, referenced as assemblies by theRowConversionbenchmark at the end (library methods only; the prototype uses x86 intrinsics):mainatc6d486d, this branch at7d2378e. "Ratio" is the faster branch round over the fastermainround. A round whose Error is larger than about half of its mean was disturbed (the M4 Pro mixes performance and efficiency cores, and 3 iterations give a wide interval); read those cells with care.With 128-bit vectors only, the main loop converts 16 bytes (4 pixels) per step, so on this machine only rows that are not a multiple of 4 pixels have a tail (1 to 3 pixels); this branch converts it with the 4-element (one pixel)
Vector128step, so forRgba32rows the scalar remainder is empty on this machine.main, round 1 / 2Rows with a tail (1, 3, 7, 15, 17, 31, 63, 255 pixels) are mostly faster: 0.54 to 0.93, the most for 3 pixels to
Rgba32(6.25 → 3.41 ns); 3 pixels toVector4, and 7, 63 and 255 pixels toRgba32, stay at 0.98 to 1.06. Rows of whole steps (4, 8, 16, 32, 64, 100, 256 pixels) should not change; they are at 0.95 to 1.07, except 8 pixels (1.49 and 1.33), where both branch rounds were disturbed.Check of the rows of whole steps with 3 launches per round (
Job.ShortRun.WithLaunchCount(3),Pixels4, 8, 16, 64, two rounds), mean ± Error in ns, round 1 / 2:mainWith more launches the 8-pixel rows are at 1.04 and 1.12 instead of 1.49 and 1.33, and 16 and 64 pixels are at 0.98 to 1.01. 4-pixel rows stay slower: 1.09 to
Vector4(3.86 and 4.07 against 4.34 and 4.20 ns) and 1.12 toRgba32(2.94 and 3.15 against 3.29 ns in the undisturbed round), about 0.3 ns per call. A 4-pixel row is one main-loop step and skips the tail, so this is the cost of the extra length test or of a change of code layout.Investigation and benchmark code
Investigation
Source path (one row of
Rgba32toVector4and back, asPixelBlender<TPixel>calls it for every blended row):PixelOperations<Rgba32>.ToUnassociatedScaledVector4→Rgba32.PixelOperations.ToUnassociatedVector4→SimdUtils.ByteToNormalizedFloat(Common/Helpers/SimdUtils.Convert.cs).HwIntrinsics.ByteToNormalizedFloatReduce(Common/Helpers/SimdUtils.HwIntrinsics.cs) takeslength - length % Vector512<byte>.Countbytes;ConvertByteToNormalizedFloatRemainderconverts the rest withbyte / (float)byte.MaxValue, one byte per iteration ([MethodImpl(MethodImplOptions.NoInlining)]).PixelOperations<Rgba32>.FromUnassociatedScaledVector4Destructive→Rgba32.PixelOperations.FromUnassociatedVector4Destructive→SimdUtils.NormalizedFloatToByteSaturate.HwIntrinsics.FloatToByteSaturateReducetakes whole multiples of 64 floats;ConvertFloatToByteRemainderconverts the rest withConvertToByte, one float per iteration.TAlphaforms (ByteToNormalizedFloat<TAlpha>,FloatToByteSaturate<TAlpha>) use the same split; their remainders runTAlpha.Applyper pixel and then the same scalar conversion.Profiles from the SVG work in ImageSharp.Drawing (
src/ImageSharp.Drawing/Svg/SVG_DESIGN.md,perfwith one thread, shares of all samples):ConvertFloatToByteRemainder7.1% andConvertByteToNormalizedFloatRemainder4.6% (measured on ImageSharp 4.1.2, which has the same split).ConvertFloatToByteRemainder9.8%.The isolated benchmark below reproduces the cost: a row of 15 pixels takes 45.2 ns to convert to vectors, a row of 16 pixels 6.2 ns; 63 pixels take 50.9 ns, 64 pixels 18.5 ns.
Benchmark to validate
Machine: Intel Xeon 2.30 GHz, 4 cores (shared cloud container, AVX-512: x86-64-v4), Ubuntu 24.04, .NET 10.0.15 (SDK 10.0.404), BenchmarkDotNet 0.15.8. Job: 5 warmup and 15 measured iterations of 100 ms, 1 launch. Error is half of the 99.9% confidence interval.
The benchmark converts one row of
Rgba32(random bytes) toVector4withPixelOperations<Rgba32>.Instance.ToUnassociatedScaledVector4, and one row ofVector4back withFromUnassociatedScaledVector4Destructive, against the prototypeProtoConvert(the main loop of the library plus the narrower steps). Neither allocates.Measured (mean per call; this run used a build made from the files below in an empty directory; a first run gave the same values within a few percent, for example 45.2 → 3.6 ns at 15 pixels):
The equality check compares the prototype with the library for every row length from 0 to 300 pixels, 20 random rows each (903,000 pixels per direction; half of the float rows hold NaN, infinities, signed zeros, and values out of range), plus the exhaustive check of the reciprocal product. Result: 0 differing bytes and floats.
What result means the fix works: the patched library gives the times of the prototype column for the lengths that end with a tail (1 to 15, 17, 31, 63, 100, 255 pixels), the same times as today for multiples of 16 pixels, and the equality check (run against the patched library and a copy of today's scalar reference) shows no difference.
How to build and run:
Bench.csproj,NuGet.config,Program.cs, and the.csfiles).dotnet build -c Debug(the project sets<Optimize>true</Optimize>; see the note on the license check).dotnet bin/Debug/net10.0/Bench.dll check.dotnet bin/Debug/net10.0/Bench.dll --filter '*.RowConversion.*'.Note on the build: the Six Labors packages run a license check in every build whose configuration does not start with
Debug; without a license key, a Release build fails. The project therefore builds theDebugconfiguration with<Optimize>true</Optimize>, and the job usesWithCustomBuildConfiguration("Debug"), so BenchmarkDotNet builds its generated project the same way and accepts it as optimized. With a license key set (SixLaborsLicenseKey), a Release build and the default job work too.Bench.csproj:NuGet.config(the prerelease packages are on the Six Labors feed):Program.cs:ProtoConvert.cs:ConvertChecks.cs:ConvertBenchmarks.cs: